import { setLocal } from '@/util/storage'
import { changeLang, getLangData } from '@api/lang'
import cn from './cn'
import en from './en'
export default {
  namespaced: true,
  state: () => ({
    lang: 'zh_CN',
    zh_CN: cn,
    en_US: en
  }),
  getters: {
    key: state => state.lang,
    // get('aaa','bbb')
    get: state => (...keys) => {
      const lang = state.lang
      const vals = []
      keys.forEach(key => {
        const val = (state[lang] && state[lang][key]) || key
        val && vals.push(val)
      })
      return vals.join('')
    },
    // tpl('{0}{d}{1}',['aaa','bbb','ccc'])
    tpl: (state, { get }) => {
      return (key, langs) => {
        const template = get(key)
        let i = 0
        return template.replace(/{\s*(.*?)\s*}/g, (_, v) => {
          const lang = (langs && langs[i++]) || ''
          return v === 'd' ? lang : get(lang)
        })
      }
    },
    print: state => state[state.lang]
  },
  mutations: {
    set(state, { key, data }) {
      state[key] = data
    }
  },
  actions: {
    async setLang({ commit, rootState }, lang) {
      const key = 'lang'
      const online = rootState.login.online
      commit('set', { key, data: lang })
      setLocal('lang/setLang', lang)
      return online && changeLang({ lang })
    },
    async setLangs({ commit, state }) {
      const key = state.lang
      await changeLang({ lang: key })
      const { data } = await getLangData()
      data && commit('set', { key, data: data[key] || {} })
    }
  }
}
